import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authAPI } from '../api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref(null)
  const token = ref(null)
  const isAuthenticated = computed(() => !!token.value)

  // 初始化：从localStorage恢复状态
  const initAuth = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')
    
    if (storedToken && storedUser) {
      token.value = storedToken
      try {
        user.value = JSON.parse(storedUser)
      } catch (e) {
        console.error('解析用户信息失败:', e)
        clearAuth()
      }
    }
  }

  // 登录（异步）
  const login = async (username, password, rememberUsername = false) => {
    try {
      const response = await authAPI.login({
        username,
        password
      })
      
      if (response && response.success) {
        token.value = response.token || response.data?.token || 'mock_token'
        user.value = response.user || response.data?.user
        
        // 持久化到localStorage
        localStorage.setItem('token', token.value)
        localStorage.setItem('user', JSON.stringify(user.value))
        
        if (rememberUsername) {
          localStorage.setItem('rememberUsername', username)
        } else {
          localStorage.removeItem('rememberUsername')
        }
        
        return { success: true }
      } else {
        return { 
          success: false, 
          message: response?.message || '登录失败' 
        }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { 
        success: false, 
        message: error.response?.data?.message || error.message || '登录失败，请检查网络连接' 
      }
    }
  }

  // 注册（异步）
  const register = async (username, password, email) => {
    try {
      const response = await authAPI.register({
        username,
        password,
        email
      })
      
      if (response && response.success) {
        return { success: true, message: response.message || '注册成功' }
      } else {
        return { 
          success: false, 
          message: response?.message || '注册失败' 
        }
      }
    } catch (error) {
      console.error('注册失败:', error)
      const errorMessage = error.response?.data?.message || error.response?.data?.error || error.message || '注册失败，请检查网络连接'
      return { 
        success: false, 
        message: errorMessage
      }
    }
  }

  // 登出
  const logout = () => {
    clearAuth()
  }

  // 清除认证信息
  const clearAuth = () => {
    user.value = null
    token.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 获取记住的用户名
  const getRememberedUsername = () => {
    return localStorage.getItem('rememberUsername') || ''
  }

  return {
    user,
    token,
    isAuthenticated,
    initAuth,
    login,
    register,
    logout,
    clearAuth,
    getRememberedUsername
  }
})
